//
//  JoinUsRecruitDetailVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/7/31.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD

class JoinUsRecruitDetailVC: UIViewController ,UITableViewDelegate ,UITableViewDataSource, JoinUsRecruitDetailHeaderCellDelegate{
    @IBOutlet weak var tableView: UITableView!
    var id: Int = 0
    var type: String = ""
    var height: CGFloat?
    var modelList = JoinUsDetailModel? ()
        {
        didSet{
            self.initRightItem()
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "招聘详情"
        self.tableView.delegate = self
        self.tableView.dataSource = self
       
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JoinUsRecruitDetailVC.tableViewReload(_:)), name:"JoinUsRecruitDetail_Noti", object: nil)
        
        let cellNib = UINib(nibName: "JoinUsRecruitDetailHeaderCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "JoinUsRecruitDetailHeaderCell")
        
        let cellNib1 = UINib(nibName: "JoinUsRecruitDetailFooterCell", bundle: nil)
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "JoinUsRecruitDetailFooterCell")
        
       getDeatilInfo(id, type: type)
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        self.tabBarController?.tabBar.hidden = true
    }
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "JoinUsRecruitDetail_Noti", object: nil)
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
        
        
    }
    func initRightItem(){
        
        //转发
        let ForwardBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ForwardBtn.setBackgroundImage(UIImage(named: "share-1-white"), forState: UIControlState.Normal)
        ForwardBtn.addTarget(self, action: #selector(self.ForwardAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Forward = UIBarButtonItem(customView: ForwardBtn)
        //收藏没有收藏
//        let img: UIImage?
//        if self.modelList!.isshoucang{
//            img = UIImage(named: "collection_selected")
//        }else{
//            img = UIImage(named: "collection")
//        }
//        let collectionBtn = UIButton(frame: CGRectMake(0, 0, 28, 28))
//        collectionBtn.setBackgroundImage(img, forState: UIControlState.Normal)
//        collectionBtn.addTarget(self, action: #selector(self.collectionAction), forControlEvents:  UIControlEvents.TouchUpInside)
//        let collection = UIBarButtonItem(customView: collectionBtn)
        
        self.navigationItem.rightBarButtonItem = Forward
        
    }
    func collectionAction(){
        if ApplicationDelegate.isLogin(){
            
        }
        
    }
    func ForwardAction(sender: UIButton){
        self.shareAction(sender)
        
    }
    
    //MARK:MobShare
    func shareAction(sender: UIButton){

        let shareParames = NSMutableDictionary()
        let url = String(format: "%@jobrecruitment/zhaopin/fenxiang/\(self.modelList!.id)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.modelList?.positionType!,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(sender, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
        
    }
    //MARK:NetingWorking
    func getDeatilInfo(id: Int, type: String) -> Void {
        DataTool.loadJoinUsDetailData(id, type: type,completionHandler: { (newModel) in
            guard let newDataes = newModel else{
                return
            }
            self.modelList = newDataes
           
            self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        })
    }


     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if modelList == nil{
            return 0
        }
        if modelList?.rmList == nil{
            return 1
        }else{
            return 2
        }
        
    }
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0{
            if modelList?.requirement == ""{
                return 526
            }else{
                let font = UIFont(name: "Helvetica", size: 16)
                height = publicMethod.getLabHeigh((self.modelList?.requirement!)!, font:font!, width:SCREEN_WIDTH - 16) + 20
                
                return 526 + height!
                
            }
        }
        if indexPath.row == 1{
            return 35 + CGFloat((modelList?.rmList?.count)!) * 90
            
        }
        return 0
        
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("JoinUsRecruitDetailHeaderCell", forIndexPath: indexPath) as! JoinUsRecruitDetailHeaderCell
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            cell.delegate = self
            cell.titleLbl.text = modelList?.title
            cell.payLbl.text = modelList?.pay
           
            cell.ptimeLbl.text = publicMethod.computationTimeDifference((modelList?.ptime)!)
            cell.browernumLbl.text = String(format: "已有%@人浏览",(modelList?.browerNum)!) 
            cell.unittypeLbl.text = modelList?.unitType
            cell.positiontypeLbl.text = modelList?.positionType
            cell.liftLbl.text = modelList?.lift
            cell.educationLbl.text = modelList?.education
           
            cell.unittypeLbl.text = modelList?.unitType
            cell.telLbl.text = modelList?.tel
            cell.requirementLbl.text = modelList?.requirement
            cell.unitcompanyLbl.text = modelList?.unitname
            cell.workArea.text = modelList?.unitarea
            cell.advertisersIv.sd_setImageWithURL(NSURL(string: (modelList?.usertimg)!), placeholderImage: UIImage(named: "placeholder"))
            cell.advertisersName.text = modelList?.username
            cell.membertypecn.text = modelList?.unittype
            cell.setCellText((modelList?.requirement)!)
            return cell
        }else{
            let cell = tableView.dequeueReusableCellWithIdentifier("JoinUsRecruitDetailFooterCell", forIndexPath: indexPath) as! JoinUsRecruitDetailFooterCell
            let cellInfo = modelList?.rmList
            cell.setCellContentWithCellInfo(cellInfo)
            return cell
            
        }
        
               
    }
    // MARK: - Table view delegate
     func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
    }
    
    //MARK:noti
    func tableViewReload(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as? Int
        let type = notification.object?.valueForKey("type") as? String
        
        getDeatilInfo(id!, type: type!)
        
    }
    //MARK:JoinUsRecruitDetailHeaderCellDelegate
    func callAction(){
        publicMethod.callPhone((self.modelList?.tel)!, withSuperView: self.view)
        
    }
    func reportAction(){
        ActionSheetMultipleStringPicker.showPickerWithTitle("举报", rows:[["电话虚假(如空号、无人接听)", "诈骗(个人虚假信息)","虚假(如职位、待遇等虚假)","涉黄违法","其他"]],initialSelection: [1,1], doneBlock: {
            picker, values, indexes in
            let obj = (indexes as! NSArray)[0] as! String
            let url = String(format: "%@hzpreport/dosave",BaseUrl)
            let paramDic = ["msg": obj, "reportid": String(self.modelList!.id!), "type": "求职招聘"]
            DataTool.reportDetail(url, param: paramDic, completionHandler: ({(newModel) in
                guard newModel != nil else {
                    return
                }
                SVProgressHUD.showSuccessWithStatus(newModel?.msg)
                
            }))
            
            return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)

        
    }
    func ivSelected() {
        
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        
        vc.userId = Int((modelList?.userid)!)
        self.navigationController?.pushViewController(vc, animated: true)
    }

}
